﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using PhotoGallery.Repositories;
using System;
using System.Linq;
using System.Security.Claims;

using System.Threading.Tasks;
using PhotoGallery.Models;
using Microsoft.EntityFrameworkCore;
using PhotoGallery.Utils;

namespace PhotoGallery.Pages
{
    public class LoginModel : PageModel
    {

        private IConfiguration _config;
        private PhotoGalleryRepository _photoGalleryRepo;

        public string Message { get;private set; }
        public LoginModel(IConfiguration config, PhotoGalleryRepository photoGalleryRepository)
        {
            
            _config = config;
            _photoGalleryRepo = photoGalleryRepository;
        }

        public async Task OnGet()
        {
            if (HttpContext.Request.Query.Any(q => q.Key == "logout") && User.Identity.IsAuthenticated)
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                RedirectFromLogin();
            }
        }

        public async Task OnPost(string username, string password, string remember)
        {

            var usr = _photoGalleryRepo.Users.IgnoreQueryFilters().FirstOrDefault(w=> w.UserName == username);
            if (usr == null)
            {
                Message = "用户不存在";               
            }
            else
            {
                if (!usr.IsEnable)
                {
                    Message = "账户被锁定,请联系管理员解锁";
                    return;
                }
                if (LoginHelper.VerifyHashedPassword(password, usr.PasswdHash, usr.Salt))
                {
                    
                    usr.FailRetry = 0;
                    usr.LastLoginTime = DateTime.Now;
                    usr.LastLoginIP = Request.HttpContext.Connection.RemoteIpAddress.ToString();
                    _photoGalleryRepo.Update(usr);
                    _photoGalleryRepo.SaveChanges();

                    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Name, usr.UserName));

                    var principle = new ClaimsPrincipal(identity);
                    var properties = new AuthenticationProperties { IsPersistent = remember == "on" };
                    await HttpContext.SignInAsync(principle, properties);

                    RedirectFromLogin();
                }
                else
                {
                    Message = "密码错误";
                    var failCount = 0;
                    int.TryParse(_config["user:MaxFailCount"], out failCount);
                    if(usr.FailRetry < failCount)
                    {
                        usr.FailRetry += 1;
                    }
                    else
                    {
                        usr.IsEnable = false;
                        Message = "密码输入错误次数太多,已被锁定";
                    }
                    _photoGalleryRepo.Update(usr);
                    _photoGalleryRepo.SaveChanges();
                }
            }
           
        }

        private void RedirectFromLogin(string query = "")
        {
            if (HttpContext.Request.Query.TryGetValue("returnUrl", out var returnUrl))
            {
                HttpContext.Response.Redirect(returnUrl.ToString() + query);
            }
            else
            {
                HttpContext.Response.Redirect("/");
            }
        }

       
    }
}
